# server.py
import time

from aiohttp import web

from properties_handler import Properties

properties = Properties("config.properties").get_properties()
port = properties.get("server.port")
routes = web.RouteTableDef()

ip_map = {}


@routes.post('/set-ip')
async def set_ip(request):
    """
    上报自己的ip，ip地址由服务器自动获得
    :param request:
    :return:
    """
    remote = request.remote
    b = await request.json()
    print(b)
    key = b.get("key")
    ip = b.get("ip")
    ipv6 = b.get("ipv6")
    mac = b.get("mac")
    if key is None or key == "":
        return web.Response("滚犊子")
    datum = {}
    if ip is None or ip == "":
        datum["ip"] = remote
    else:
        datum["ip"] = ip
    if ipv6 is not None and ipv6 != "":
        datum["ipv6"] = ipv6
    if mac is not None and mac != "":
        datum["mac"] = mac
    datum["time"] = time.strftime("%Y-%m-%d %H:%M:%S")
    ip_map[key] = datum
    body = {
        "msg": "success"
    }
    return web.json_response(body)


@routes.get('/gbnfsrghget-all-ip')
async def get_all_ip(request):
    """
    获得所有ip配置
    :param request:
    :return:
    """
    return web.json_response(ip_map)


@routes.get('/get/{key}')
async def get_by_key(request):
    """
    获得所有ip配置
    :param request:
    :return:
    """
    key = request.match_info['key']
    return web.json_response(ip_map.get(key))


@routes.get('/register')
async def register(request):
    return web.Response(text="not supported")


@routes.get('/ifconfig')
async def register(request):
    remote = request.remote
    return web.Response(text=remote)


app = web.Application()
app.add_routes(routes)
web.run_app(app, port=port)
